package com.ktgj.flight.controller;


import cn.hutool.core.codec.Base64Decoder;
import com.alibaba.fastjson.JSONObject;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.FlightOrderConstants;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.xml.XElement;
import com.ktgj.customer.api.domain.CustomerIdVoApi;
import com.ktgj.flight.common.linkstar.domain.airReIssuePrice.AirReIssuePriceRequest;
import com.ktgj.flight.common.linkstar.domain.airReIssuePrice.ReIssuePriceResponse;
import com.ktgj.flight.domain.*;
import com.ktgj.flight.domain.InterfaceEntity.MoOrderPayRequest;
import com.ktgj.flight.domain.InterfaceEntity.MoOrderPayResponse;
import com.ktgj.flight.domain.InterfaceEntity.*;
import com.ktgj.flight.domain.vo.BillPayment;
import com.ktgj.flight.domain.vo.PaymentCallbackVo;
import com.ktgj.flight.mapper.*;
import com.ktgj.flight.service.*;
import com.ktgj.flight.service.impl.IflightOrderServiceImpl;
import com.ktgj.pay.api.RemotePayService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@ControllerAdvice
@RestController
@RequestMapping("/callback")
public class CallbackController {

    @Autowired
    private IFlightOrderInfoTicketsService flightOrderInfoTicketsService;
    @Autowired
    private IFlightService flightService;
    @Autowired
    private RemotePayService payService;
    @Autowired
    private IFlightOrderChangeTicketsService changeTicketsService;
    @Autowired
    private IFlightOrderInfoService orderInfoService;
    @Autowired
    private FlightOrderCashInfoMapper flightOrderCashInfoMapper;
    @Autowired
    private IflightOrderMapper iflightOrderMapper;
    @Autowired
    private IflightPaymentMapper iflightPaymentMapper;
    @Autowired
    private FlightOrderInfoMapper flightOrderInfoMapper;
    @Autowired
    private FinanceConsignPymtRecordMapper financeConsignPymtRecordMapper;

    /**
     * 瑞丽支付回调
     * @param request
     * @param response
     */
    @RequestMapping("/drHuiFuCallback")
    public void drHuiFuCallback(HttpServletRequest request,HttpServletResponse response){
        HuiFuTicketResponse huiFuTicketResponse = new HuiFuTicketResponse();
        try {
            request.setCharacterEncoding("gb2312");
            huiFuTicketResponse.setVersion(request.getParameter("RespCode"));
            huiFuTicketResponse.setBalance(request.getParameter("ErrorMsg"));
            huiFuTicketResponse.setChkValue(request.getParameter("Balance"));
            huiFuTicketResponse.setDrawResult(request.getParameter("RetUrl"));
            huiFuTicketResponse.setDrawResultDes(request.getParameter("CmdId"));
            huiFuTicketResponse.setGUID(request.getParameter("MerId"));
            huiFuTicketResponse.setOrderAmt(request.getParameter("TrxId"));
            huiFuTicketResponse.setReqType(request.getParameter("OrdAmt"));
            huiFuTicketResponse.setReqType(request.getParameter("CurCode"));
            huiFuTicketResponse.setReqType(request.getParameter("Pid"));
            huiFuTicketResponse.setReqType(request.getParameter("OrdId"));
            huiFuTicketResponse.setReqType(request.getParameter("MerPriv"));
            huiFuTicketResponse.setReqType(request.getParameter("RetType"));
            huiFuTicketResponse.setReqType(request.getParameter("DivDetails"));
            huiFuTicketResponse.setReqType(request.getParameter("GateId"));
            huiFuTicketResponse.setReqType(request.getParameter("ChkValue"));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        PrintWriter printWriter = null;
        try {
            response.setCharacterEncoding("UTF-8");
            printWriter = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (printWriter != null) {
            if (huiFuTicketResponse.getDrawResult().equals("000000")) {
                printWriter.write("PNR_SUCC");
            } else {
                try {
                    printWriter.write(new String("PNR_FAIL" + huiFuTicketResponse.getDrawResultDes().getBytes("GB2312")));
                } catch (UnsupportedEncodingException e) {
                    System.out.println("发送回调信息失败！");
                    e.printStackTrace();
                }
            }
            printWriter.close();
        }
    }

    //汇付天下出票回调
    @RequestMapping("/huifuTicketCallback")
    public void huifuCallack(HttpServletResponse response, HttpServletRequest request) {
        HuiFuTicketResponse huiFuTicketResponse = new HuiFuTicketResponse();
        try {
            //获取所有的请求参数列表
            //request.getParameterMap();
            request.setCharacterEncoding("gb2312");
            huiFuTicketResponse.setVersion(request.getParameter("Version"));
            huiFuTicketResponse.setBalance(request.getParameter("Balance"));
            huiFuTicketResponse.setChkValue(request.getParameter("ChkValue"));
            huiFuTicketResponse.setDrawResult(request.getParameter("DrawResult"));
            huiFuTicketResponse.setDrawResultDes(request.getParameter("DrawResultDes"));
            huiFuTicketResponse.setGUID(request.getParameter("GUID"));
            huiFuTicketResponse.setOrderAmt(request.getParameter("OrderAmt"));
            huiFuTicketResponse.setReqType(request.getParameter("ReqType"));
            huiFuTicketResponse.setAgentPct(request.getParameter("AgencyPct"));
            huiFuTicketResponse.setBalance(request.getParameter("Balance"));
            huiFuTicketResponse.setAgentFee(request.getParameter("AgentFee"));
            huiFuTicketResponse.setRsv1(request.getParameter("Rsv1"));
            huiFuTicketResponse.setRsv2(request.getParameter("Rsv2"));
            List<FlightOrderInfoTickets> lstFilghtOrderTicket = flightOrderInfoTicketsService.selectOrderInfoTicketByOrderId(Long.parseLong(huiFuTicketResponse.getGUID()));
            String[] arrInfo = huiFuTicketResponse.getDrawResultDes().split(";");
            int pos = 0;
            for (String tmpInfo : arrInfo)
            {
                String[] arrTmpInfo = tmpInfo.split("\\+");
                FlightOrderInfoTickets orderInfoTickets = lstFilghtOrderTicket.get(pos);
                orderInfoTickets.setTicketNo(arrTmpInfo[0]);
                flightOrderInfoTicketsService.updateFlightOrderInfoTickets(orderInfoTickets);
                pos++;
            }
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        PrintWriter printWriter = null;
        try {
            response.setCharacterEncoding("UTF-8");
            printWriter = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (printWriter != null) {
            if (huiFuTicketResponse.getDrawResult().equals("000000")) {
                printWriter.write("PNR_SUCC");
            } else {
                try {
                    printWriter.write(new String("PNR_FAIL" + huiFuTicketResponse.getDrawResultDes().getBytes("GB2312")));
                } catch (UnsupportedEncodingException e) {
                    System.out.println("发送回调信息失败！");
                    e.printStackTrace();
                }
            }
            printWriter.close();
        }
    }

    /**
     * 易宝出票回调
     * @param request
     */
    @RequestMapping("/yeepayTicketCallback")
    public void yeepayCallBack(HttpServletRequest request) {
        try {
            request.setCharacterEncoding("GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        YeepayPaymentResponse yeepayPaymentResponse = new YeepayPaymentResponse();
        yeepayPaymentResponse.p1_MerId = request.getParameter("p1_MerId");
        yeepayPaymentResponse.r0_Cmd = request.getParameter("r0_Cmd");
        yeepayPaymentResponse.r1_Code = request.getParameter("r1_Code");
        yeepayPaymentResponse.r2_TrxId = request.getParameter("r2_TrxId");
        yeepayPaymentResponse.r3_Amt = request.getParameter("r3_Amt");
        yeepayPaymentResponse.r4_Cur = request.getParameter("r4_Cur");
        yeepayPaymentResponse.r5_Pid = request.getParameter("r5_Pid");
        yeepayPaymentResponse.r6_Order = request.getParameter("r6_Order");  //这个订单号不为空证明支付成功
        yeepayPaymentResponse.r7_Uid = request.getParameter("r7_Uid");
        yeepayPaymentResponse.r8_MP = request.getParameter("r8_MP");
        yeepayPaymentResponse.r9_BType = request.getParameter("r9_BType");
        yeepayPaymentResponse.hmac = request.getParameter("hmac");
        yeepayPaymentResponse.errorMsg = request.getParameter("errorMsg");
        System.out.println(yeepayPaymentResponse.p1_MerId);
        System.out.println(yeepayPaymentResponse.r6_Order);
        System.out.println(yeepayPaymentResponse.hmac);
        System.out.println(yeepayPaymentResponse.errorMsg);
        System.out.println(yeepayPaymentResponse.r2_TrxId);
    }


    /**
     * 银联二维码回调函数
     * @param response
     * @param request
     */
    @RequestMapping("/unionPayQRCodeCallback")
    public void UnionPayQRCodeCallback(HttpServletResponse response, HttpServletRequest request)
    {
        //http://106.38.39.137:8080/flight/callback/unionPayQRCodeCallback  银联二维码回调地址
        PaymentCallbackVo paymentCallbackVo = new PaymentCallbackVo();
        String parameter = request.getParameter("billPayment");
        BillPayment parseObject = JSONObject.parseObject(parameter, BillPayment.class);
        paymentCallbackVo.setBillPayment(parseObject);
        paymentCallbackVo.setMid(request.getParameter("mid"));//商户号
        paymentCallbackVo.setTid(request.getParameter("tid"));//终端号
        paymentCallbackVo.setInstMid(request.getParameter("instMid"));//业务类型
        paymentCallbackVo.setBillNo(request.getParameter("billNo"));//账单号
        paymentCallbackVo.setBillQRCode(request.getParameter("billQRCode"));//账单二维码
        paymentCallbackVo.setBillStatus(request.getParameter("billStatus"));//账单状态
        paymentCallbackVo.setBillDesc(request.getParameter("billDesc"));//账单描述
        paymentCallbackVo.setMemberId(request.getParameter("memberId"));//会员号
        paymentCallbackVo.setCounterNo(request.getParameter("counterNo"));//桌号、柜台号、房间号
        paymentCallbackVo.setMerName(request.getParameter("merName"));//商户名称
        paymentCallbackVo.setMemo(request.getParameter("memo"));//付款附言
        paymentCallbackVo.setNotifyId(request.getParameter("notifyId"));//支付通知ID
        paymentCallbackVo.setSecureStatus(request.getParameter("secureStatus"));//担保状态
        paymentCallbackVo.setCompleteAmount(request.getParameter("completeAmount"));//担保完成金额（分）
        paymentCallbackVo.setBillDate(request.getParameter("billDate"));//订单时间，格式yyyy-MM-dd
        paymentCallbackVo.setCreateTime(request.getParameter("createTime"));//账单创建时间，格式yyyy-MM-dd HH:mm:ss
        paymentCallbackVo.setSign(request.getParameter("sign"));//签名
        paymentCallbackVo.setExtraBuyerInfo(request.getParameter("extraBuyerInfo"));//用户额外信息

        FlightOrderInfo orderInfo = new FlightOrderInfo();
        if (paymentCallbackVo.getBillStatus().equals("PAID")) {
            MoOrderPayRequest moRequest = new MoOrderPayRequest();
            moRequest.OrderID = paymentCallbackVo.getBillNo().substring(4);
            moRequest.PayMode = BusinessTypeConstants.UnionPayQRCode.getValue();
            FlightOrderInfo flightOrderInfo = orderInfoService.selectFlightOrderInfoById(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
            if (!flightOrderInfo.getGuestPymtStsId().equals(FlightOrderConstants.payd.getValue()) && !flightOrderInfo.getStatus().equals(FlightOrderConstants.noTravel.getValue())) {
                MoOrderPayResponse payOrder = flightService.payOrder(moRequest);
                System.out.println("订单号：" + paymentCallbackVo.getBillNo() + "\n支付信息：" + payOrder.PayInfo.toString());
                orderInfo.setOrderId(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
                orderInfo.setPayType(BusinessTypeConstants.UnionPayQRCode.getValue());
                orderInfo.setGuestPymtStsId(FlightOrderConstants.payd.toString()); //支付成功
                orderInfo.setBillNo(paymentCallbackVo.getBillNo());
                orderInfo.setPayTime(new Date());
                orderInfoService.updateFlightOrderInfo(orderInfo);
            }
            /*String amount = (Integer.parseInt(paymentCallbackVo.getCompleteAmount()) / 100) + "." + (Integer.parseInt(paymentCallbackVo.getCompleteAmount()) % 100);
            flightOrderCashInfoMapper.addFlightOrderCashInfo(paymentCallbackVo.getBillNo().substring(4),
                    paymentCallbackVo.getBillNo(), amount, BusinessTypeConstants.UnionPayQRCode.getValue(), null);*/
        } else {
            Date date = new Date();
            FinanceConsignPymtRecord financeConsignPymtRecord = new FinanceConsignPymtRecord();
            FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
            financeConsignPymtRecord.setOrderId(flightOrderInfo.getOrderId());
            financeConsignPymtRecord.setEmployeeId(10l);
            financeConsignPymtRecord.setPaymentTime(date);
            financeConsignPymtRecord.setPayStart("false");

            Long amount = Long.valueOf(paymentCallbackVo.getCompleteAmount()) / 100;

            financeConsignPymtRecord.setPaymentAmount(new BigDecimal(amount));
            financeConsignPymtRecord.setOperationTime(date);
            financeConsignPymtRecord.setPymtType(EmHelper.cardType.UnionPayQR.getValue());
            financeConsignPymtRecord.setOrderAmount(new BigDecimal(amount));
            financeConsignPymtRecord.setCreateTime(date);
            financeConsignPymtRecord.setRemark("支付失败");
            financeConsignPymtRecordMapper.insertFinanceConsignPymtRecord(financeConsignPymtRecord);

            orderInfo.setOrderId(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
            orderInfo.setGuestPymtStsId(FlightOrderConstants.failPay.toString()); //支付失败
            orderInfoService.updateFlightOrderInfo(orderInfo);
        }

        PrintWriter printWriter;
        response.setCharacterEncoding("UTF-8");
        try {
            printWriter = response.getWriter();
            printWriter.write("SUCCESS");
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 银联二维码退款回调
     * */
    @RequestMapping("/unionPayQRCodeRefund")
    public void unionPayQRCodeRefund(HttpServletResponse response, HttpServletRequest request){
        // todo
    }

    /**
     * 改签订单银联二维码回调函数
     * @param response
     * @param request
     */
    @RequestMapping("/changeUnionPayQRCodeCallback")
    public void changeUnionPayQRCodeCallback(HttpServletResponse response, HttpServletRequest request) {
        PaymentCallbackVo paymentCallbackVo = new PaymentCallbackVo();
        String parameter = request.getParameter("billPayment");
        BillPayment parseObject = JSONObject.parseObject(parameter, BillPayment.class);
        paymentCallbackVo.setBillPayment(parseObject);
        paymentCallbackVo.setMid(request.getParameter("mid"));//商户号
        paymentCallbackVo.setTid(request.getParameter("tid"));//终端号
        paymentCallbackVo.setInstMid(request.getParameter("instMid"));//业务类型
        paymentCallbackVo.setBillNo(request.getParameter("billNo"));//账单号
        paymentCallbackVo.setBillQRCode(request.getParameter("billQRCode"));//账单二维码
        paymentCallbackVo.setBillStatus(request.getParameter("billStatus"));//账单状态
        paymentCallbackVo.setBillDesc(request.getParameter("billDesc"));//账单描述
        paymentCallbackVo.setMemberId(request.getParameter("memberId"));//会员号
        paymentCallbackVo.setCounterNo(request.getParameter("counterNo"));//桌号、柜台号、房间号
        paymentCallbackVo.setMerName(request.getParameter("merName"));//商户名称
        paymentCallbackVo.setMemo(request.getParameter("memo"));//付款附言
        paymentCallbackVo.setNotifyId(request.getParameter("notifyId"));//支付通知ID
        paymentCallbackVo.setSecureStatus(request.getParameter("secureStatus"));//担保状态
        paymentCallbackVo.setCompleteAmount(request.getParameter("completeAmount"));//担保完成金额（分）
        paymentCallbackVo.setBillDate(request.getParameter("billDate"));//订单时间，格式yyyy-MM-dd
        paymentCallbackVo.setCreateTime(request.getParameter("createTime"));//账单创建时间，格式yyyy-MM-dd HH:mm:ss
        paymentCallbackVo.setSign(request.getParameter("sign"));//签名
        paymentCallbackVo.setExtraBuyerInfo(request.getParameter("extraBuyerInfo"));//用户额外信息

        if (paymentCallbackVo.getBillStatus().equals("PAID")) {
            FlightOrderChangeTickets orderChangeTickets = changeTicketsService.selectFlightOrderChangeTicketsById(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
            List<FlightOrderInfoTickets> infoTickets = flightOrderInfoTicketsService.selectOrderInfoTicketByOrderId(orderChangeTickets.getOrderId());

            AirReIssuePriceRequest priceRequest = new AirReIssuePriceRequest();
            priceRequest.setDepartureTime(String.valueOf(orderChangeTickets.getDepartureTime()));
            priceRequest.setArrivalTime(String.valueOf(orderChangeTickets.getArrivalTime()));
            priceRequest.setFlightNo(orderChangeTickets.getFlight());
            priceRequest.setCabin(orderChangeTickets.getCabin());
            priceRequest.setTicketNo(orderChangeTickets.getOldTicketNo());
            priceRequest.setOrderId(orderChangeTickets.getPnr());
            priceRequest.setEquipment(orderChangeTickets.getPlaneStyle());
            priceRequest.setDifferencePrice(true);
            ReIssuePriceResponse price = flightService.testAirReIssuePrice(priceRequest);

            MoOrderChangeRequest changeRequest = new MoOrderChangeRequest();
            ChangeSegementInfo segementInfo = new ChangeSegementInfo();
            segementInfo.TakeoffDate = orderChangeTickets.getDepartureTime();
            segementInfo.ArrivalTime = orderChangeTickets.getArrivalTime();
            segementInfo.DestinFlight = orderChangeTickets.getFlight().substring(2);
            segementInfo.NewDPort = infoTickets.get(0).getOrgAirport();
            segementInfo.NewAPort = infoTickets.get(0).getDstAirport();
            segementInfo.airline = orderChangeTickets.getAirliner();
            segementInfo.NewClass = orderChangeTickets.getCabin();
            segementInfo.PlaneStyle = orderChangeTickets.getPlaneStyle();
            changeRequest.ListChangeSegementInfo.add(segementInfo);
            changeRequest.newOrderId = paymentCallbackVo.getBillNo().substring(4);
            changeRequest.pnr = orderChangeTickets.getPnr();
            changeRequest.ticketNo = orderChangeTickets.getOldTicketNo();
            changeRequest.TicketFee = orderChangeTickets.getTicketPrice();
            changeRequest.PayAmount = new BigDecimal(price.getPayPrice());
            changeRequest.channelType = 14;
            if (!orderChangeTickets.getStatus().equals(FlightOrderConstants.ticketing.getValue())) {
                MoOrderChangeResponse changeResponse = flightService.ticketChangeFlight(changeRequest);
                if (changeResponse.IsSuccess) {
                    FlightOrderInfoTickets tickets = new FlightOrderInfoTickets();
                    tickets.setOrderId(orderChangeTickets.getOrderId());
                    tickets.setTicketNo(orderChangeTickets.getOldTicketNo());
                    tickets.setStatus(FlightOrderConstants.changeTicketSuccess.getValue());
                    flightOrderInfoTicketsService.updateFlightOrderInfoTicket(tickets);
                }
                orderChangeTickets.setChangeFee(new BigDecimal(price.getPayPrice()));
                orderChangeTickets.setPayType(BusinessTypeConstants.UnionPayQRCode.getValue());
                orderChangeTickets.setBillNo(paymentCallbackVo.getBillNo());
                orderChangeTickets.setStatus(FlightOrderConstants.ticketing.getValue());
                changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                System.out.println("改签单号：" + changeResponse.ApplicationId);
            }
        }
        else {
            Date date = new Date();
            FinanceConsignPymtRecord financeConsignPymtRecord = new FinanceConsignPymtRecord();
            FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
            financeConsignPymtRecord.setOrderId(flightOrderInfo.getOrderId());
            financeConsignPymtRecord.setEmployeeId(10l);
            financeConsignPymtRecord.setPaymentTime(date);
            financeConsignPymtRecord.setPayStart("false");

            Long amount = Long.valueOf(paymentCallbackVo.getCompleteAmount()) / 100;

            financeConsignPymtRecord.setPaymentAmount(new BigDecimal(amount));
            financeConsignPymtRecord.setOperationTime(date);
            financeConsignPymtRecord.setPymtType(EmHelper.cardType.UnionPayQR.getValue());
            financeConsignPymtRecord.setOrderAmount(new BigDecimal(amount));
            financeConsignPymtRecord.setCreateTime(date);
            financeConsignPymtRecord.setRemark("支付失败");
            financeConsignPymtRecordMapper.insertFinanceConsignPymtRecord(financeConsignPymtRecord);
        }
        PrintWriter printWriter;
        response.setCharacterEncoding("UTF-8");
        try {
            printWriter = response.getWriter();
            printWriter.write("SUCCESS");
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/phoneSoundPayCallback")
    public void phoneSoundPayCallback(HttpServletResponse response, HttpServletRequest request)
    {
        //http://106.38.39.137:8080/flight/callback/phoneSoundPayCallback
        try
        {
            request.setCharacterEncoding("UTF-8");
//            response_xml=String(Base64Decode(UrlDecode(request.getParameter(response_text),UTF-8)),UTF-8)
            String response_xml = Base64Decoder.decodeStr(request.getParameter("response_text"));
            XElement root = XElement.loadXml(response_xml);
            PhoneSoundCallback phoneSoundCallback = new PhoneSoundCallback();
            phoneSoundCallback.setAccountType(root.element("AccountType").getValue());
            phoneSoundCallback.setAcqSsn(root.element("AcqSsn").getValue());
            phoneSoundCallback.setAmount(root.element("Amount").getValue());
            phoneSoundCallback.setAsynAddress(root.element("AsynAddress").getValue());
            phoneSoundCallback.setCurrency(root.element("Currency").getValue());
            phoneSoundCallback.setDescription(root.element("Description").getValue());
            phoneSoundCallback.setMAC(root.element("MAC").getValue());
            phoneSoundCallback.setMerchantNo(root.element("MerchantNo").getValue());
            phoneSoundCallback.setMerchantOrderNo(root.element("MerchantOrderNo").getValue());
            phoneSoundCallback.setMethod(root.element("Method").getValue());
            phoneSoundCallback.setOrderNo(root.element("OrderNo").getValue());
            phoneSoundCallback.setOrderState(root.element("OrderState").getValue());
            phoneSoundCallback.setOrderType(root.element("OrderType").getValue());
            phoneSoundCallback.setProcCode(root.element("ProcCode").getValue());
            phoneSoundCallback.setProcessCode(root.element("ProcessCode").getValue());
            phoneSoundCallback.setRemark(root.element("Remark").getValue());
            phoneSoundCallback.setRespCode(root.element("RespCode").getValue());
            phoneSoundCallback.setSettleDate(root.element("SettleDate").getValue());
            phoneSoundCallback.setTerminalNo(root.element("TerminalNo").getValue());
            phoneSoundCallback.setTsNo(root.element("TsNo").getValue());
            phoneSoundCallback.setUpsNo(root.element("UpsNo").getValue());
            phoneSoundCallback.setUserPayedTime(root.element("UserPayedTime").getValue());
            phoneSoundCallback.setVersion(root.element("Version").getValue());
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
//        String response_text=UrlEncode(Base64Encode(Xml.getBytes(UTF-8)),UTF-8)
//        String response_xml=new String(Base64Decode(UrlDecode(request.getParameter(response_text),UTF-8)),UTF-8)
    }

    /**
     * 微信小程序支付回调
     * @param resultMap
     */
    @RequestMapping("/wechatPayCallback")
    public void wechatPayCallback(HttpServletResponse response, @RequestBody Map<String, String> resultMap) throws IOException {
        String resXml = "";
        boolean result = payService.isPaySuccessful(resultMap);
        System.out.println("回调成功**************************");
        String returnCode = resultMap.put("return_code", resultMap.get("return_code"));
        String resultCode = resultMap.put("result_code", resultMap.get("result_code"));
        String outTradeNo = resultMap.put("out_trade_no", resultMap.get("out_trade_no"));
        String transaction_id = resultMap.put("transaction_id", resultMap.get("transaction_id"));
        if (result) {
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS")) {//交易成功
                if (outTradeNo != null) {//商户订单号
                    MoOrderPayRequest moRequest = new MoOrderPayRequest();
                    moRequest.OrderID = outTradeNo;
                    moRequest.PayMode = BusinessTypeConstants.Wechat.getValue();
                    FlightOrderInfo flightOrderInfo = orderInfoService.selectFlightOrderInfoById(Long.valueOf(outTradeNo));
                    if (!flightOrderInfo.getGuestPymtStsId().equals(FlightOrderConstants.payd.getValue()) && !flightOrderInfo.getStatus().equals(FlightOrderConstants.noTravel.getValue())) {
                        MoOrderPayResponse payOrder = flightService.payOrder(moRequest);
                        System.out.println("订单号：" + outTradeNo + "\n支付信息：" + payOrder.PayInfo.toString());

                        FlightOrderInfo orderInfo = orderInfoService.selectFlightOrderInfo(outTradeNo); //获取订单主表信息
                        orderInfo.setPayType(BusinessTypeConstants.Wechat.getValue());
                        orderInfo.setPayTime(new Date());
                        orderInfo.setBillNo(transaction_id);
                        orderInfoService.updateFlightOrderInfo(orderInfo);
                        if (payOrder != null) {
                            //通知微信服务器已经支付成功
                            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                        } else {
                            //支付成功，但是逻辑出错，请求再次回调
                            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                        }
                    }
                }
            }
            else {
                Date date = new Date();
                FinanceConsignPymtRecord financeConsignPymtRecord = new FinanceConsignPymtRecord();
                FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(Long.valueOf(outTradeNo));
                financeConsignPymtRecord.setOrderId(flightOrderInfo.getOrderId());
                financeConsignPymtRecord.setEmployeeId(10l);
                financeConsignPymtRecord.setPaymentTime(date);
                financeConsignPymtRecord.setPayStart("false");
                financeConsignPymtRecord.setPaymentAmount(flightOrderInfo.getPayAmount());
                financeConsignPymtRecord.setOperationTime(date);
                financeConsignPymtRecord.setPymtType(EmHelper.cardType.Applets.getValue());
                financeConsignPymtRecord.setOrderAmount(flightOrderInfo.getPayAmount());
                financeConsignPymtRecord.setCreateTime(date);
                financeConsignPymtRecord.setRemark("支付失败");
                financeConsignPymtRecordMapper.insertFinanceConsignPymtRecord(financeConsignPymtRecord);
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        response.setContentType("text/xml");
        response.getWriter().write(resXml);
    }

    /**
     * 改签微信小程序支付回调
     * @param resultMap
     */
    @RequestMapping("/wechatPayChangeCallback")
    public void wechatPayChangeCallback(@RequestBody Map<String, String> resultMap) {
        boolean result = payService.isPaySuccessful(resultMap);
        String returnCode = resultMap.put("return_code", resultMap.get("return_code"));
        String resultCode = resultMap.put("result_code", resultMap.get("result_code"));
        String outTradeNo = resultMap.put("out_trade_no", resultMap.get("out_trade_no"));
        String transaction_id = resultMap.put("transaction_id", resultMap.get("transaction_id"));
        if (result) {
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS")) {//交易成功
                if (outTradeNo != null) {//商户订单号
                    FlightOrderChangeTickets orderChangeTickets = changeTicketsService.selectFlightOrderChangeTicketsById(Long.valueOf(outTradeNo));
                    List<FlightOrderInfoTickets> infoTickets = flightOrderInfoTicketsService.selectOrderInfoTicketByOrderId(orderChangeTickets.getOrderId());

                    AirReIssuePriceRequest request = new AirReIssuePriceRequest();
                    request.setDepartureTime(String.valueOf(orderChangeTickets.getDepartureTime()));
                    request.setArrivalTime(String.valueOf(orderChangeTickets.getArrivalTime()));
                    request.setFlightNo(orderChangeTickets.getFlight());
                    request.setCabin(orderChangeTickets.getCabin());
                    request.setTicketNo(orderChangeTickets.getOldTicketNo());
                    request.setOrderId(orderChangeTickets.getPnr());
                    request.setEquipment(orderChangeTickets.getPlaneStyle());
                    request.setDifferencePrice(true);
                    ReIssuePriceResponse price = flightService.testAirReIssuePrice(request);

                    MoOrderChangeRequest changeRequest = new MoOrderChangeRequest();
                    ChangeSegementInfo segementInfo = new ChangeSegementInfo();
                    segementInfo.TakeoffDate = orderChangeTickets.getDepartureTime();
                    segementInfo.ArrivalTime = orderChangeTickets.getArrivalTime();
                    segementInfo.DestinFlight = orderChangeTickets.getFlight().substring(2);
                    segementInfo.NewDPort = infoTickets.get(0).getOrgAirport();
                    segementInfo.NewAPort = infoTickets.get(0).getDstAirport();
                    segementInfo.airline = orderChangeTickets.getAirliner();
                    segementInfo.NewClass = orderChangeTickets.getCabin();
                    segementInfo.PlaneStyle = orderChangeTickets.getPlaneStyle();
                    changeRequest.ListChangeSegementInfo.add(segementInfo);
                    changeRequest.newOrderId = outTradeNo;
                    changeRequest.pnr = orderChangeTickets.getPnr();
                    changeRequest.ticketNo = orderChangeTickets.getOldTicketNo();
                    changeRequest.TicketFee = orderChangeTickets.getTicketPrice();
                    changeRequest.PayAmount = new BigDecimal(price.getPayPrice());
                    changeRequest.channelType = 14;
                    if (!orderChangeTickets.getStatus().equals(FlightOrderConstants.ticketing.getValue())) {
                        MoOrderChangeResponse response = flightService.ticketChangeFlight(changeRequest);
                        orderChangeTickets.setChangeFee(new BigDecimal(price.getPayPrice()));
                        orderChangeTickets.setPayType(BusinessTypeConstants.Wechat.getValue());
                        orderChangeTickets.setStatus(FlightOrderConstants.ticketing.getValue());
                        orderChangeTickets.setBillNo(transaction_id);
                        changeTicketsService.updateFlightOrderChangeTickets(orderChangeTickets);
                        System.out.println("改签单号：" + response.ApplicationId);
                    }
                }
            }
            else {
                Date date = new Date();
                FinanceConsignPymtRecord financeConsignPymtRecord = new FinanceConsignPymtRecord();
                FlightOrderInfo flightOrderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(Long.valueOf(outTradeNo));
                financeConsignPymtRecord.setOrderId(flightOrderInfo.getOrderId());
                financeConsignPymtRecord.setEmployeeId(10l);
                financeConsignPymtRecord.setPaymentTime(date);
                financeConsignPymtRecord.setPayStart("false");
                financeConsignPymtRecord.setPaymentAmount(flightOrderInfo.getPayAmount());
                financeConsignPymtRecord.setOperationTime(date);
                financeConsignPymtRecord.setPymtType(EmHelper.cardType.Applets.getValue());
                financeConsignPymtRecord.setOrderAmount(flightOrderInfo.getPayAmount());
                financeConsignPymtRecord.setCreateTime(date);
                financeConsignPymtRecord.setRemark("支付失败");
                financeConsignPymtRecordMapper.insertFinanceConsignPymtRecord(financeConsignPymtRecord);
            }
        }
    }

    @RequestMapping("/wechatRefundCallback")
    public void wechatRefundCallback(@RequestBody Map<String, String> resultMap)
    {
        System.out.println(resultMap);
    }

    /**
     * 国际机票银联二维码回调
     */
    @RequestMapping("/unionPayQRCallback")
    public void unionPayQRCallback(HttpServletResponse response, HttpServletRequest request)
    {
        //http://106.38.39.137:8080/flight/callback/unionPayQRCodeCallback  银联二维码回调地址
        PaymentCallbackVo paymentCallbackVo = new PaymentCallbackVo();
        String parameter = request.getParameter("billPayment");
        BillPayment parseObject = JSONObject.parseObject(parameter, BillPayment.class);
        paymentCallbackVo.setBillPayment(parseObject);
        paymentCallbackVo.setMid(request.getParameter("mid"));//商户号
        paymentCallbackVo.setTid(request.getParameter("tid"));//终端号
        paymentCallbackVo.setInstMid(request.getParameter("instMid"));//业务类型
        paymentCallbackVo.setBillNo(request.getParameter("billNo"));//账单号
        paymentCallbackVo.setBillQRCode(request.getParameter("billQRCode"));//账单二维码
        paymentCallbackVo.setBillStatus(request.getParameter("billStatus"));//账单状态
        paymentCallbackVo.setBillDesc(request.getParameter("billDesc"));//账单描述
        paymentCallbackVo.setMemberId(request.getParameter("memberId"));//会员号
        paymentCallbackVo.setCounterNo(request.getParameter("counterNo"));//桌号、柜台号、房间号
        paymentCallbackVo.setMerName(request.getParameter("merName"));//商户名称
        paymentCallbackVo.setMemo(request.getParameter("memo"));//付款附言
        paymentCallbackVo.setNotifyId(request.getParameter("notifyId"));//支付通知ID
        paymentCallbackVo.setSecureStatus(request.getParameter("secureStatus"));//担保状态
        paymentCallbackVo.setCompleteAmount(request.getParameter("completeAmount"));//担保完成金额（分）
        paymentCallbackVo.setBillDate(request.getParameter("billDate"));//订单时间，格式yyyy-MM-dd
        paymentCallbackVo.setCreateTime(request.getParameter("createTime"));//账单创建时间，格式yyyy-MM-dd HH:mm:ss
        paymentCallbackVo.setSign(request.getParameter("sign"));//签名
        paymentCallbackVo.setExtraBuyerInfo(request.getParameter("extraBuyerInfo"));//用户额外信息

        if (paymentCallbackVo.getBillStatus().equals("PAID")) {
            IflightOrder iflightOrder = iflightOrderMapper.selectIflightOrderByOrderNum(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
            iflightOrder.setPaystatus(FlightOrderConstants.payd.getValue());
            iflightOrder.setStatus(FlightOrderConstants.payd.getValue());
            iflightOrderMapper.updateIflightOrder(iflightOrder);

            IflightPayment iflightPayment = new IflightPayment();
            iflightPayment.setOrderid(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
            iflightPayment.setJsjid(iflightOrder.getCustomerId());
            iflightPayment.setPartnername(EmHelper.cardType.UnionPayQR.getValue());
            String amount = (Integer.parseInt(paymentCallbackVo.getCompleteAmount())) / 100 + "." + (Integer.parseInt(paymentCallbackVo.getCompleteAmount()) % 100);
            iflightPayment.setAmount(new BigDecimal(amount));
            iflightPayment.setTradeorderid(iflightOrder.getOrderid().toString());
            iflightPayment.setTradetime(new Date());
            iflightPayment.setStatus(1l);
            iflightPayment.setStatusmsg("银联二维码支付成功");
            iflightPayment.setExternalbillno("5676" + paymentCallbackVo.getBillNo());
            iflightPaymentMapper.updateIflightPayment(iflightPayment);
        } else {
            IflightOrder iflightOrder = iflightOrderMapper.selectIflightOrderByOrderNum(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
            iflightOrder.setPaystatus(FlightOrderConstants.waitPay.getValue());
            iflightOrder.setStatus(FlightOrderConstants.failPay.getValue());
            iflightOrderMapper.updateIflightOrder(iflightOrder);

            IflightPayment iflightPayment = new IflightPayment();
            iflightPayment.setOrderid(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
            iflightPayment.setJsjid(iflightOrder.getCustomerId());
            iflightPayment.setPartnername(EmHelper.cardType.UnionPayQR.getValue());
            String amount = (Integer.parseInt(paymentCallbackVo.getCompleteAmount())) / 100 + "." + (Integer.parseInt(paymentCallbackVo.getCompleteAmount()) % 100);
            iflightPayment.setAmount(new BigDecimal(amount));
            iflightPayment.setTradeorderid(iflightOrder.getOrderid().toString());
            iflightPayment.setTradetime(new Date());
            iflightPayment.setStatus(0l);
            iflightPayment.setStatusmsg("银联二维码支付失败");
            iflightPaymentMapper.updateIflightPayment(iflightPayment);
        }

        PrintWriter printWriter;
        response.setCharacterEncoding("UTF-8");
        try {
            printWriter = response.getWriter();
            printWriter.write("success");
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 国际机票银联二维码退款回调
     * */
    @RequestMapping("/retreatUnionPayQRCallback")
    public void retreatUnionPayQRCallback(HttpServletResponse response, HttpServletRequest request){
        // todo
    }
}
